import copy
import pandas as pd


def sum_percent(df,ratio,col,groupby_cols):
    groupby = df.groupby(groupby_cols)
    group_sum = groupby[col].sum() / ratio
    if len(groupby_cols) == 1:
        group_percent = group_sum.transform(lambda x: x / x.sum()).rename(f'{col}占比')
    else:
        group_percent =copy.deepcopy(group_sum)
        for i in group_percent.index:
            group_percent[i] = group_percent[i]/group_sum[i[0:len(i)-1]].sum()
    group_percent = group_percent.rename(f'{col}占比')

    group_sort = copy.deepcopy(group_sum)
    group_sort = group_sort.sort_values(ascending=False)
    n = 1
    for i in group_sort.index:
        group_sort[i] = n
        n = n+1
    group_sort = group_sort.rename(f'{col}排序')
    result = merge([group_sum, group_percent,group_sort])
    return result


def count_percent(df,groupby_cols):
    col = '计数'
    groupby = df.groupby(groupby_cols)
    group_count = groupby.size().rename(col)
    if len(groupby_cols) == 1:
        group_percent = group_count.transform(lambda x: x / x.sum()).rename(f'{col}占比')
    else:
        group_percent = copy.deepcopy(group_count)
        for i in group_percent.index:
            group_percent[i]=group_percent[i].astype(float)
            group_percent[i] = group_percent[i]/ float(group_count[i[0:len(i)-1]].sum())
    group_percent = group_percent.rename(f'{col}占比')

    group_sort = copy.deepcopy(group_count)
    group_sort = group_sort.sort_values(ascending=False)
    n = 1
    for i in group_sort.index:
        group_sort[i] = n
        n = n + 1
    group_sort = group_sort.rename(f'{col}排序')

    result = merge([group_count, group_percent,group_sort])
    return result


def merge(groupbys):
    result = pd.concat(groupbys, axis=1, join='inner')
    return result
